package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Api(tags = "通用接口")
@Slf4j
@RequestMapping("/admin/common")
@RestController
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file){
        log.info("文件上传:{}", file.getOriginalFilename());
        //0.通过UUID生成一个随机字符串,用作文件名
        //获取文件后缀  eg:  1.jpg
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;  // xxx-xxx-xxx.jpg

        //1.调用AliOssUtil工具类方法,将文件上传到阿里云
        try {
            String url = aliOssUtil.upload(file.getBytes(), fileName);
            //2.将图片路径返回给前端
            return Result.success(url);
        } catch (IOException e) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }

    }
}
